package com.umessage.hotel.rest;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.riversoft.weixin.common.jsapi.JsAPISignature;
import com.riversoft.weixin.mp.base.AppSetting;
import com.riversoft.weixin.mp.jsapi.JsAPIs;
import com.umessage.hotel.domain.HotelInfo;
import com.umessage.hotel.domain.PictureInfo;
import com.umessage.hotel.model.HotelIndexModel;
import com.umessage.hotel.model.HotelModel;
import com.umessage.hotel.model.PictureModel;
import com.umessage.hotel.service.DepositOrderService;
import com.umessage.hotel.service.HotelInfoService;
import com.umessage.hotel.service.MemberInfoService;
import com.umessage.hotel.service.OrderInfoService;
import com.umessage.hotel.service.PictureInfoService;
import com.umessage.hotel.util.RestResult;
import com.umessage.hotel.util.RestResultGenerator;
import com.umessage.system.domain.Dict;
import com.umessage.system.service.DictService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api("酒店管理")
@RestController
@RequestMapping(value = "/rest/hotels")
public class HotelResource {
	/**
	 * 新注册
	 */
	public static final String USER_GRADE_NEW = "1";
	/**
	 * 会员（手机号已绑定）
	 */
	public static final String USER_GRADE_MEMBER = "2";
	/**
	 * 已确认订单
	 */
	public static final String ORDER_STATUS_CONFIRM = "1";

	@Autowired
	private HotelInfoService hotelInfoService;
	@Autowired
	private DictService dictService;
	@Autowired
	private PictureInfoService picService;
	@Autowired
	private MemberInfoService memberInfoService;
	@Autowired
	private OrderInfoService orderService;
	@Autowired
	private DepositOrderService depositOrderService;

	private HotelModel getHotelInfo(String hotelId,String type) {
		HotelInfo hotel = this.hotelInfoService.findHotelsById(hotelId);

		if (hotel == null)
			return null;

		HotelModel hotelModel = new HotelModel();
		hotelModel.setHotelId(hotel.getHotelId());
		hotelModel.setHotelName(hotel.getHotelName());
		hotelModel.setSummary(hotel.getSummary());
		hotelModel.setContact(hotel.getPhone());
		 /*hotelModel.setProvince(hotel.getProvince());
		 hotelModel.setCity(hotel.getCity());
		 hotelModel.setDistrict(hotel.getDistrict());
		 hotelModel.setStreet(hotel.getStreet());*/
		hotelModel.setLatitude(hotel.getLatitude());
		hotelModel.setLongitude(hotel.getLongitude());
		hotelModel.setAdress(hotel.getAddress());
		hotelModel.setAddTime(hotel.getAddTime().toString());
		hotelModel.setMarkOne(hotel.getMarkOne());
		hotelModel.setMarkTwo(hotel.getMarkTwo());
		if(hotel.getWifiStatus()!=null) {
			hotelModel.setWifiStatus(hotel.getWifiStatus());
		}
		if(hotel.getWifiName()!=null) {
			hotelModel.setWifiName(hotel.getWifiName());
		}
		if(hotel.getWifiPassword()!=null) {
			hotelModel.setWifiPassword(hotel.getWifiPassword());
		}
		if(StringUtils.isNotBlank(hotel.getInvoiceType())){
			if("0".equals(hotel.getInvoiceType())) {
				hotelModel.setInvoiceType(null);
			}else{
				hotelModel.setInvoiceType(Arrays.asList(hotel.getInvoiceType().split(",")));
			}
		}
		Dict dict = new Dict();
		dict.setTableName("t_hotel_info");
		// 设施
		if("1".equals(type)) {
			if (hotel.getFacilities() != null) {
				Map<String, String> facMap = new LinkedHashMap<>();
				dict.setFieldName("facilities");
				List<Dict> facDicts = this.dictService.findAllDicts(dict);
				String[] strs1 = hotel.getFacilities().split(",");
				for (Dict fac : facDicts) {
					for (int i = 0; i < strs1.length; i++) {
						if (fac.getKeyy().equals(strs1[i].toString())) {
							facMap.put(fac.getKeyy(), fac.getValuee());
						}
					}
				}
				hotelModel.setFacilities(facMap);
			}
		}
		// 标签
		if(type!=null) {
			if (hotel.getTag() != null) {
				Map<String, String> tags = new HashMap<String, String>();
				dict.setFieldName("tag");
				String[] strs2 = hotel.getTag().split(",");
				List<Dict> tagDicts = this.dictService.findAllDicts(dict);
				for (Dict tag : tagDicts) {
					for (int i = 0; i < strs2.length; i++) {
						if (tag.getKeyy().equals(strs2[i].toString())) {
							tags.put(tag.getKeyy(), tag.getValuee());
						}
					}
				}
				hotelModel.setTag(tags);
			}
		}
		// 房策
		if("2".equals(type)) {
			if (hotel.getPolicies() != null) {
				Map<String, String> policies = new HashMap<String, String>();
				String[] strs3 = hotel.getPolicies().split(",");
				dict.setFieldName("policies");
				List<Dict> polsDicts = this.dictService.findAllDicts(dict);
				for (Dict pol : polsDicts) {
					for (int i = 0; i < strs3.length; i++) {
						if (pol.getKeyy().equals(strs3[i].toString())) {
							policies.put(pol.getKeyy(), pol.getValuee());
						}
					}
				}
				hotelModel.setPolicies(policies);
			}
		}
		PictureInfo pic = new PictureInfo();
		pic.setTableName("t_hotel_info");
		pic.setTableId(hotelId);
		pic.setType("0");
		List<PictureInfo> pics = this.picService.findPictures(pic);
		List<PictureModel> picsModel = new ArrayList<>();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				PictureModel picModel = new PictureModel();
				picModel.setPicHref(pics.get(i).getPicHref());
				picModel.setPicUrl(pics.get(i).getPicUrl());
				picModel.setSort(pics.get(i).getSort());
				picsModel.add(picModel);
			}
		}
		hotelModel.setBannerPics(picsModel);
		return hotelModel;
	}

	/**
	 * 获取酒店信息
	 * 
	 * @param orderId
	 * @return
	 */
	@ApiOperation(value = "获取酒店信息", notes = "获取酒店信息")
	@RequestMapping(value = "/{hotelId}", method = RequestMethod.GET)
	public RestResult<HotelModel> loadHotel(ServletRequest request, @PathVariable(name = "hotelId") String hotelId,@RequestParam(required=true)String type) {
		HotelModel hotelInfo = getHotelInfo(hotelId,type);
		if (hotelInfo != null) {
			return RestResultGenerator.genSuccessResult(hotelInfo);
		}
		return RestResultGenerator.genErrorResult("invalid hotel id");

	}

	/**
	 * 小程序首页信息 今日详情
	 */
	@ApiOperation(value = "小程序首页", notes = "首页今日详情")
	@RequestMapping(value = "/index/today", method = RequestMethod.GET)
	public RestResult<HotelIndexModel> hotelIndexToday(ServletRequest request) {
		try {
			String hotelId = (String) request.getAttribute("issuer");
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			String startTime = LocalDate.now().format(formatter);
			String endTime = LocalDate.now().format(formatter);
			// 新增用户
			Integer registerCount = this.memberInfoService.countNewMember(hotelId, USER_GRADE_NEW, startTime, endTime);
			// 新增会员
			Integer vipCount = this.memberInfoService.countNewMember(hotelId, USER_GRADE_MEMBER, startTime, endTime);
			// 成交订单
			Integer orderCount = this.orderService.countOrders(hotelId, ORDER_STATUS_CONFIRM, startTime, endTime);
			// 充值金额
			BigDecimal depositMoney = this.depositOrderService.taotalPay(hotelId, startTime, endTime);
			// 总收入
			BigDecimal ordersIncome = this.orderService.countOrdersIncome(hotelId, startTime, endTime);// 订单总收入
			HotelIndexModel hotelIndexModel = new HotelIndexModel();
			hotelIndexModel.setUserCount(registerCount);
			hotelIndexModel.setVipCount(vipCount);
			hotelIndexModel.setOrderCount(orderCount);
			hotelIndexModel.setDepositMoney(depositMoney);
			hotelIndexModel.setTotalIncome(ordersIncome);
			return RestResultGenerator.genSuccessResult(hotelIndexModel);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}

	}

	/**
	 * 小程序首页信息 统计
	 */
	@ApiOperation(value = "小程序首页", notes = "首页统计详情")
	@RequestMapping(value = "/index/total", method = RequestMethod.GET)
	public RestResult<HotelIndexModel> hotelIndexTotal(ServletRequest request,
			@RequestParam(required = true) String startTime, @RequestParam(required = true) String endTime) {
		try {
			String hotelId = (String) request.getAttribute("issuer");
			/*
			 * DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			 * String startTime = null; String endTime = LocalDate.now().format(formatter);
			 */
			// 新增用户
			Integer registerCount = this.memberInfoService.countNewMember(hotelId, USER_GRADE_NEW, startTime, endTime);
			// 新增会员
			Integer vipCount = this.memberInfoService.countNewMember(hotelId, USER_GRADE_MEMBER, startTime, endTime);
			// 成交订单
			Integer orderCount = this.orderService.countOrders(hotelId, ORDER_STATUS_CONFIRM, startTime, endTime);
			// 充值金额
			BigDecimal depositMoney = this.depositOrderService.taotalPay(hotelId, startTime, endTime);
			// 总收入
			BigDecimal ordersIncome = this.orderService.countOrdersIncome(hotelId, startTime, endTime);// 订单总收入
			HotelIndexModel hotelIndexModel = new HotelIndexModel();
			hotelIndexModel.setUserCount(registerCount);
			hotelIndexModel.setVipCount(vipCount);
			hotelIndexModel.setOrderCount(orderCount);
			hotelIndexModel.setDepositMoney(depositMoney);
			hotelIndexModel.setTotalIncome(ordersIncome);
			return RestResultGenerator.genSuccessResult(hotelIndexModel);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

	@ApiOperation(value = "签名", notes = "签名")
	@RequestMapping(value = "/signature", method = RequestMethod.GET)
	public RestResult signature(String url) {
		try {

			String url2 = URLDecoder.decode(url);
			System.out.println(url2);
			AppSetting appSetting = new AppSetting("wx252804fce6f4375e", "afb6ab98f71131f162871e88977c559e");
			JsAPIs jsapi = JsAPIs.with(appSetting);
			JsAPISignature signature = jsapi.createJsAPISignature(url2);
			JSONObject obj = new JSONObject();
			obj.put("appid", signature.getAppId());
			obj.put("timestamp", signature.getTimestamp());
			obj.put("nonceStr", signature.getNonce());
			obj.put("url", signature.getUrl());
			obj.put("signature", signature.getSignature());
			return RestResultGenerator.genSuccessResult(obj);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

}
